<?php

include('mysql.php');
include('simple_html_dom.php');
include('seo_url.php');
include('utf8.php');

$db = new MySQL("localhost", "root", "", "crawler");

function error_handler($errno, $errstr, $errfile, $errline) {
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            $error = 'Notice';
            break;
        case E_WARNING:
        case E_USER_WARNING:
            $error = 'Warning';
            break;
        case E_ERROR:
        case E_USER_ERROR:
            $error = 'Fatal Error';
            break;
        default:
            $error = 'Unknown';
            break;
    }
    echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
    return true;
}

// Error Handler
set_error_handler('error_handler');

download();

function download($url_image = "http://s4.haivl.com/data/photos2/20120507/b94265630aad47a9b6aace4a6024e5f7/medium-8826726a47ff4f7aa5202e159c2d18af-650.jpg") {
    $temp = explode("/", $url_image);
    $directory = 'E:\www\www\crawler/image/data/funny/' . $temp[5]; //or anything else you want
    if (!is_dir($directory)) {
        mkdir($directory, 0777);
    }
    $overwrite = true; //or false if image has to be renamed on duplicate
    $urlinfo = parse_url($url_image);
    $filename = basename($urlinfo['path']);
    $target = $directory . '/' . $filename;
    if (file_exists($target) && !$overwrite) {
        //break up file in parts:
        $pathinfo = pathinfo($target);
        //max 50 tries
        $max = 50;
        //loop
        for ($i = 1; $i <= $max; $i++) {
            $target = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '[' . $i . '].' . $pathinfo['extention'];
            //break on success, do not use file_exists to avoid race
            $fh = @fopen($target, 'x');
            if ($fh)
                break;
        }
        //alternatively, if you don't care about the name, you can just:
        //$target = tempnam($directory);
        if (!$fh)
            die('Too many retries, no unique filename found.');
    } else {
        $fh = fopen($target, 'w');
    }
    $check = fwrite($fh, file_get_contents($url_image));
    fclose($fh);

    $ext = strrchr($target, '.');
    $image_name = md5(time());
    $new_name = $directory . '/' . $image_name . $ext;
    rename($target, $new_name);
    echo (($check) ? 'Successfully saved ' . $new_name . '<br>' : 'Failure' . '<br>');
    
    //update image name = data/funny/' . $temp[5] . $image_name . $ext;
}

?>